package com.kele.shiro.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kele.shiro.entity.User;
import com.kele.shiro.service.UserService;
import com.kele.shiro.utils.ApplicationContextUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Arrays;
import java.util.List;

public class CustomRealm extends AuthorizingRealm {
	@Autowired
	UserService userService;

	//比对权限和角色工具
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

		final User principal = (User) principalCollection.getPrimaryPrincipal();

		List<String> roles  = getRolesFromDB(principal);

		List<String> permissions = getPermissionsFromDB(principal);

		SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
		simpleAuthorizationInfo.addRoles(roles);
		simpleAuthorizationInfo.addStringPermissions(permissions);

		return simpleAuthorizationInfo;

	}

	// 查询角色
	private List<String> getRolesFromDB(User principal) {

		return userService.findRoles(principal);
	}

	//查询权限
	private List<String> getPermissionsFromDB(User principal) {

		return userService.findPermissions(principal);
	}


	//登录比对通道
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

		final String principal = (String) authenticationToken.getPrincipal();
		System.out.println(principal);
		User user = getUserFromDB(principal);
		if (user==null){
			throw new UnknownAccountException();
		}
		// 注意：这里需要返回该token对应的AuthenticationInfo对象，并不需要对密码进行比对
		// 比对密码的过程由shiro后续自动完成
		// 因为密码通常会由加密算法和加盐生成，shiro封装了密码比对过程
		// 这里只需要把数据库中的用户名和密码封装到 AuthenticationInfo 对象中即可。
		return new SimpleAuthenticationInfo(user,user.getPassword(),ByteSource.Util.bytes( user.getSalt() ),this.getName());

	}

	private User getUserFromDB(String principal) {

		QueryWrapper<User> queryWrapper=new QueryWrapper<>(  );
		QueryWrapper< User > user=queryWrapper.eq( "username",principal );

		//根据用户名查询
		User user1=userService.getOne( user );

		if (user1==null){
			return null;
		}
		return  user1;
	}
}
